const mongoose = require('mongoose')
const db = 'mongodb://localhost/local'

// const glob = require('glob')
// const { resolve }  = require('path')

// exports.initSchemas = () =>{
//   glob.sync(resolve(__dirname,'./schema/','**/*.js')).forEach(require)
// }

mongoose.Promise = global.Promise

exports.connect = () => {
  let maxConnectTimes = 0
  // 连接数据库
  mongoose.connect(db)
  return new Promise((resolve, reject) => {

    // 增加数据库连接的事件监听
    mongoose.connection.on('disconnected', () => {
      console.log('**********数据库断开连接**********')
      // 进行重连
      if (maxConnectTimes < 3) {
        maxConnectTimes++
        mongoose.connect(db)
      } else {
        reject()
        throw new Error('数据库出现问题,重连失败过多...')
      }
    })

    // 数据库出现错误的时候
    mongoose.connection.on('error', err => {
      console.log(err)
      console.log('***********数据库错误***********')
      if (maxConnectTimes < 3) {
        maxConnectTimes++
        mongoose.connect(db)
      } else {
        reject(err)
        throw new Error('数据库出现问题...')
      }
    })

    // 连接打开时
    mongoose.connection.on('open', () => {
      console.log('MongoDB connected successfully!')
    })
  })
}